package com.issac.demo.pooled2.mydatasource;

import lombok.Setter;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.sql.*;

/**
 * @author: ywy
 * @date: 2023-06-28
 * @desc:
 */
@Setter
public class ConnectionFactory implements PooledObjectFactory<MyConnection> {

    private ObjectPool<MyConnection> pool;

    @Override
    public PooledObject<MyConnection> makeObject() throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection(
                "jdbc:mysql://localhost/foodie-shop-dev",
                "root", "rootroot"
        );
        MyConnection myConnection = new MyConnection();
        myConnection.setConnection(connection);
        myConnection.setPool(pool);
        return new DefaultPooledObject<>(myConnection);
    }

    @Override
    public void destroyObject(PooledObject<MyConnection> p) throws Exception {
        p.getObject().close();
    }

    @Override
    public boolean validateObject(PooledObject<MyConnection> p) {
        MyConnection connection = p.getObject();
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement("select 1 from dual");
            ResultSet resultSet = preparedStatement.executeQuery();
            return resultSet.getInt(1) == 1;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void activateObject(PooledObject<MyConnection> p) throws Exception {

    }

    @Override
    public void passivateObject(PooledObject<MyConnection> p) throws Exception {
        MyConnection myConnection = p.getObject();
        if (myConnection.getStatement() != null) {
            myConnection.getStatement().close();
        }

    }
}
